package com.cn.sl.server.api.system.file.service.impl

import com.cn.sl.server.api.system.file.config.LocalFileUploadConfig
import com.cn.sl.server.api.system.file.exception.UploadFileException
import com.cn.sl.server.api.system.file.service.FileUploadService
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.web.multipart.MultipartFile
import java.io.File
import java.io.IOException
import java.nio.file.Files

/**
 * 本地文件上传
 *
 * @author 阮雪峰
 */
class LocalFileUploadServiceImpl(
    val config: LocalFileUploadConfig
) : FileUploadService {
    companion object {
        val logger: Logger = LoggerFactory.getLogger(LocalFileUploadServiceImpl::class.java)
    }

    override fun upload(file: MultipartFile, key: String): String {
        return try {
            val file1 = File(config.filePath + key)
            if (!file1.parentFile.exists() && file1.parentFile.mkdirs()) {
                logger.info("创建文件夹成功（{}）", config.filePath + key)
            }
            file.transferTo(file1)
            key.replace(File.separator, "/")
        } catch (e: IOException) {
            throw UploadFileException(e)
        }
    }

    override fun remove(key: String) {
        val f = File(key)
        try {
            Files.delete(f.toPath())
        } catch (e: IOException) {
            logger.error("删除文件失败，路径：{}", f.path)
        }
    }
}
